<?php

namespace app\components;

use Yii;
use yii\helpers\Json;

class PaidanService
{
    private $appId;
    private $token;
    private $header;
    private $host;

    const EVENT_INFO_URL = '/open-api/case-info/';

    public function __construct()
    {
        $this->host = isset(Yii::$app->params['paidan']['host']) ? Yii::$app->params['paidan']['host'] : '';
        $this->appId = isset(Yii::$app->params['paidan']['app_id']) ? Yii::$app->params['paidan']['app_id'] : '';
        $this->token = isset(Yii::$app->params['paidan']['token']) ? Yii::$app->params['paidan']['token'] : '';
        $this->header = ['appid:'.$this->appId,'token:'.$this->token];
    }

    public function getEventInfo($eventId) {
        $params['header'] = $this->header;
        $url = $this->host . '/' . self::EVENT_INFO_URL . $eventId;
        $respone = $this->request($url,'get',$params);
        $respone = json_decode($respone, true);
        $data = [];
        if (isset($respone['code']) && $respone['code'] == 200 && isset($respone['data'])) {
            $data = $respone['data'];
        }

        return $data;
    }

    public function request(string $url, string $method = "get", $params = [], $isJson = false)
    {
        $header = [];
        if (isset($params['header']) && !empty($params['header']) && is_array($params['header'])) {
            $header = $params['header'];
        }

        $method = strtolower($method);
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        if ($method == 'post') {
            if ($isJson) {
                $httpHeader = ['Content-Type: application/json', 'Content-Length: ' . strlen($params),];
                $header = array_merge($header, $httpHeader);
                $params = is_string($params) ? $params : Json::encode($params);
            }
            curl_setopt($curl, CURLOPT_POST, 1); //post提交内容
            curl_setopt($curl, CURLOPT_POSTFIELDS, $params);
        }
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        $response = curl_exec($curl);
        return $response;
    }
}